<template>
  <a-modal
    :width="800"
    v-model:visible="state.visible"
    centered
    title="设置分区和标签"
    @cancel="cancel"
  >
    <a-form
      :model="state.formData"
      :rules="state.formRules"
      :labelCol="{ span: 3 }"
      ref="formRef"
    >
      <!-- 分区 -->
      <a-form-item label="分区" name="partition">
        <a-spin :spinning="state.selectLoading" tip="加载中...">
          <div class="cascader">
            <a-cascader
              v-model:value="state.formData.partition"
              @change="partitionChange"
              :options="state.typeList"
              placeholder="选择分区"
              :getPopupContainer="
                (triggerNode) => {
                  return triggerNode.parentNode;
                }
              "
              expand-trigger="hover"
            >
            </a-cascader>
          </div>
        </a-spin>
      </a-form-item>
      <!-- 标签 -->
      <a-form-item label="标签" name="tagname" class="tag-select">
        <a-select
          v-model:value="state.formData.tagname"
          mode="tags"
          style="width: 100%"
          placeholder="按回车键Enter创建标签"
          :maxTagCount="10"
          :maxTagTextLength="10"
          @change="tagChange($event)"
        >
        </a-select>
        <div class="tip_text">还可以添加{{ remainingTags }}个标签</div>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="cancel">取消</a-button>
      <a-button type="primary" @click="submit">确定</a-button>
    </template>
  </a-modal>
</template>

<script setup>
import { ref, reactive, defineEmits, defineProps, computed, h } from "vue";
import { SmileOutlined, MehOutlined } from "@ant-design/icons-vue";
import request from "@/common/utils/request";
import { message } from "ant-design-vue";
const props = defineProps({});
const emit = defineEmits(["success"]);
const state = reactive({
  visible: false,
  formData: {
    partition: null,
    tagname: [],
  },
  formRules: {
    partition: [{ required: true, message: "请选择分区", trigger: "change" }],
    tagname: [{ required: true, message: "请填写标签", trigger: "change" }],
  },
  typeList: [], //分区列表
  openType: "",
  accountList: [],
  editId: null,
  selectLoading: true,
});
const showModal = (info) => {
  if (info.openType == "single") {
    state.editId = info.editId;
    let findIndex = info.accountList.findIndex((ele) => ele.id == info.editId);
    state.formData.partition = info.accountList[findIndex].partition;
    state.formData.tagname = info.accountList[findIndex].tagname;
  } else if (info.openType == "all") {
    state.formData.partition = null;
    state.formData.tagname = [];
  }
  state.accountList = info.accountList;
  state.openType = info.openType;
  getTypeList();
  state.visible = true;
};
const getTypeList = async () => {
  let params = {
    account_ids: state.accountList.map((item) => item.id),
  };
  state.selectLoading = true;
  try {
    await request
      .post("/work_ai", "/org/platformAccount/filter/typeList", params)
      .then((res) => {
        state.selectLoading = false;
        if (res.result) {
          const typeListKeys = Object.keys(res.result); // 获取 typeList 对象的键
          const firstKey = typeListKeys[0]; // 获取第一个键
          state.typeList = res.result[firstKey]?.typeList?.map((item) => {
            return {
              ...item,
              label: item.name,
              value: item.id,
              children: item.children.map((ele) => {
                return {
                  ...ele,
                  label: h("span", [
                    `${ele.name}`,
                    h(
                      "span",
                      {
                        style: {
                          color: "#999",
                          fontSize: "10px",
                          marginLeft: "10px",
                        },
                      },
                      ele.description
                    ),
                  ]),
                  value: ele.id,
                };
              }),
            };
          });
        }
      })
      .catch(() => {
        state.selectLoading = false;
      });
  } catch (error) {
    state.selectLoading = false;
  }
};
const remainingTags = computed(() => {
  const tagCount = state.formData.tagname?.length || 0;
  return Math.max(10 - tagCount, 0); // 保证返回值不小于0
});
const tagChange = (event) => {
  if (event.length && event[event.length - 1].length > 20) {
    message.error("单个标签长度不能超过20个字符");
    state.formData.tagname[state.formData.tagname.length - 1] =
      state.formData.tagname[state.formData.tagname.length - 1].substring(
        0,
        20
      );
  }
  if (event.length > 10) {
    message.warning("最多添加10个标签");
    state.formData.tagname = state.formData.tagname.filter(
      (tag, index) => index < 10
    );
  }
};
const initData = () => {
  state.accountList = [];
  state.editId = null;
  formRef.value.resetFields();
  state.openType = "";
};
let formRef = ref(null);
const submit = () => {
  formRef.value.validate().then(async (values) => {
    try {
      const parentId = state.formData.partition[1];
      const childrenItem = state.typeList
        ?.flatMap((item) => item.children)
        .find((ele) => ele.id == parentId);

      if (state.openType == "all") {
        state.accountList.forEach((item) => {
          item.archive_type = {
            id: childrenItem?.id,
            name: childrenItem?.name,
            parent: childrenItem?.parent,
            description: childrenItem?.description,
            parent_name: state.typeList[0]?.name,
            parent_description: state.typeList[0]?.description,
            account_id: item.id,
          };
          item.tagname = state.formData.tagname;
          item.partition = state.formData.partition;
        });
      } else if (state.openType == "single") {
        const findIndex = state.accountList.findIndex(
          (item) => item.id == state.editId
        );
        state.accountList[findIndex] = {
          ...state.accountList[findIndex],
          archive_type: {
            id: childrenItem?.id,
            name: childrenItem?.name,
            parent: childrenItem?.parent,
            description: childrenItem?.description,
            parent_name: state.typeList[0]?.name,
            parent_description: state.typeList[0]?.description,
            account_id: state.editId,
          },
          tagname: state.formData.tagname,
          partition: state.formData.partition,
        };
      }

      state.visible = false;
      emit("success", state.accountList);
      initData();
    } catch (error) {
      console.log(error);
    }
  });
};
const cancel = () => {
  state.visible = false;
  initData();
};
defineExpose({
  showModal,
  cancel,
});
</script>

<style lang="less" scoped>
.cascader {
  :deep(.ss-cascader-menus) {
    padding: 20px;
    &::-webkit-scrollbar {
      width: 8px; /* 滚动条的宽度 */
      height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
      display: none;
    }
    &::-webkit-scrollbar-thumb {
      background: #eeeeee; /* 滑块的背景颜色 */
      border-radius: 10px; /* 滑块的圆角 */
    }
  }
  :deep(.ss-cascader-menu) {
    height: 100%;
    &:nth-child(1) {
      max-height: 400px;
      width: 130px;
      overflow-y: auto;
      .ss-cascader-menu-item-content {
        padding: 5px;
      }
      .ss-cascader-menu-item-active {
        color: var(--ss-primary-color);
      }
      &::-webkit-scrollbar {
        width: 8px; /* 滚动条的宽度 */
        height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
        display: none;
      }
      &::-webkit-scrollbar-thumb {
        background: #eeeeee; /* 滑块的背景颜色 */
        border-radius: 10px; /* 滑块的圆角 */
      }
    }
    &:nth-child(2) {
      width: 400px;
      max-height: 400px;
      overflow-y: auto;
      .ss-cascader-menu-item-active {
        color: var(--ss-primary-color);
      }
      .ss-cascader-menu-item-content {
        width: 100%;
        padding: 5px;
        white-space: nowrap; /* 强制文本在一行显示 */
        overflow: hidden; /* 隐藏溢出部分 */
        text-overflow: ellipsis; /* 用省略号表示溢出部分 */
      }
      .ss-cascader-menu-item-expand .ss-cascader-menu-item-expand-icon,
      .ss-cascader-menu-item-loading-icon {
        display: none;
      }
      &::-webkit-scrollbar {
        width: 8px; /* 滚动条的宽度 */
        height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
        display: none;
      }
      &::-webkit-scrollbar-thumb {
        background: #eeeeee; /* 滑块的背景颜色 */
        border-radius: 10px; /* 滑块的圆角 */
      }
    }
    // &:nth-child(3) {
    //   width: 300px;
    //   max-height: 400px;
    //   overflow-y: auto;
    //   color: #999;
    //   .ss-cascader-menu-item-active {
    //     color: var(--ss-primary-color);
    //   }
    //   .ss-cascader-menu-item-content {
    //     width: 100%;
    //     padding: 5px;
    //     white-space: nowrap; /* 强制文本在一行显示 */
    //     overflow: hidden; /* 隐藏溢出部分 */
    //     text-overflow: ellipsis; /* 用省略号表示溢出部分 */
    //   }
    //   &::-webkit-scrollbar {
    //     width: 8px; /* 滚动条的宽度 */
    //     height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
    //     display: none;
    //   }
    //   &::-webkit-scrollbar-thumb {
    //     background: #eeeeee; /* 滑块的背景颜色 */
    //     border-radius: 10px; /* 滑块的圆角 */
    //   }
    // }
  }
}
.tag-select {
  position: relative;
  .tip_text {
    position: absolute;
    right: 0;
    bottom: 0;
    color: #858585;
    padding: 5px;
  }
}
</style>
